package com.eco.fanliapp.utils;

import com.google.gson.Gson;
import com.google.gson.annotations.SerializedName;

import java.net.URLEncoder;
import java.util.Date;

public class MrwSoDwzUtils {
    final static String CREATE_API = "http://mrw.so/api.php";
    final static String TOKEN = "5d79a92e91d2c402baf8df5f@8805971718cce689ef42bdb27dce13ab"; // TODO:设置Token

    class UrlResponse {

        @SerializedName("url")
        private String url;

        @SerializedName("err")
        private String err;

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getErr() {
            return err;
        }

        public void setErr(String err) {
            this.err = err;
        }
    }

    /**
     * 创建短网址
     *
     * @param longUrl
     *            长网址：即原网址
     *        termOfValidity
     *            有效期：默认值为long-term
     * @return  成功：短网址
     *          失败：返回空字符串
     */
    public static String createShortUrl(String longUrl) {
        String urlEncoder = "";
        try {

            String expireDate = DateFormatUtils.getNowDateDay(DateUtils.updateMonthByDate(new Date(),12));
            urlEncoder = URLEncoder.encode(longUrl, "utf-8");
            String requestUrl = CREATE_API + "?url=" + urlEncoder + "&format=json&key=" + TOKEN + "&expireDate=" + expireDate;

            String shortUrls = HttpUtils.sendGet(requestUrl, "");

            UrlResponse urlResponse = new Gson().fromJson(shortUrls, UrlResponse.class);

            if (urlResponse.getErr() == null || "".equals(urlResponse.getErr())) {
                return urlResponse.getUrl();
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}
